package com.pig4cloud.pig.ads.gdt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.ads.gdt.service.GdtAccesstokenService;
import com.pig4cloud.pig.ads.gdt.service.GdtAdReportService;
import com.pig4cloud.pig.ads.pig.mapper.AdPicturePlatformMapper;
import com.pig4cloud.pig.ads.pig.mapper.gdt.GdtAdMapper;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.api.entity.AdPicturePlatform;
import com.pig4cloud.pig.api.entity.ResponseBean;
import com.pig4cloud.pig.api.enums.GdtAdEnum;
import com.pig4cloud.pig.api.gdt.dto.GdtAdReport;
import com.pig4cloud.pig.api.gdt.entity.GdtAd;
import com.pig4cloud.pig.api.gdt.vo.GdtAdVo;
import com.pig4cloud.pig.ads.clickhouse3399.mapper.GdtAdReportMapper;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.api.util.MapUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @description:
 * @author: nml
 * @time: 2020/12/18 14:19
 **/
@Log4j2
@Service
public class GdtAdReportServiceImpl implements GdtAdReportService {

	@Value(value = "${gdt_ad_update_url}")
	private String gdtAdUpdateUrl;

	@Value(value = "${gdt_url}")
	private String gdtUrl;

	@Resource
	private GdtAdReportMapper gdtAdReportMapper;

	@Resource
	private GdtAdMapper gdtAdMapper;

	@Resource
	private GdtAccesstokenService gdtAccesstokenService;

	@Resource
	private AdPicturePlatformMapper adPicturePlatformMapper;

	@Autowired
	private AdvService advService;

	/*
	 *  查询广告列表数据
	 * */
	@Override
	public R getGdtAdReport(GdtAdVo gdtAdVo) {
		//广点通报表
		IPage<GdtAdReport> result = new Page<>();

		//获取当前账号下 广点通广告账户列表
		List<String> advertiserList = advService.getOwnerAdv(SecurityUtils.getUser().getId(), PlatformTypeEnum.GDT.getValue());
		//List<String> advertiserList = null;
		if (null == advertiserList || advertiserList.size() <= 0){
			return R.ok(result,"未绑定广告账户，无数据可查看");
		}
		//设置参数:广告账户ids集合
		//前端没传广告账户参数，通过当前账户查询
		if (null == gdtAdVo.getAdvertiserIds() || gdtAdVo.getAdvertiserIds().length <=0){
			gdtAdVo.setAccountIds(advertiserList);
		}else {//前端有传广告账户参数
			List<String> advertiserIdsList = Arrays.asList(gdtAdVo.getAdvertiserIds());
			gdtAdVo.setAccountIds(advertiserIdsList);
		}
		//处理时间参数
		String sdate = gdtAdVo.getSdate();
		String edate = gdtAdVo.getEdate();
		if (StringUtils.isBlank(sdate) || StringUtils.isBlank(edate)){
			return R.failed("时间参数异常");
		}
		gdtAdVo.setSdate(sdate);
		gdtAdVo.setEdate(edate);

		try {
			result = gdtAdReportMapper.selectGdtAdReport(gdtAdVo);
			List<GdtAdReport> records = result.getRecords();
			//查询图片url + onOff
			if (records.size()>0){
				for (int i = 0; i < records.size(); i++) {
					//1 预览：图片url
					records.get(i).setImageUrl("");
					//如果广告创意字段不为空
					if (StringUtils.isNotBlank(records.get(i).getAdcreativeElements())){
						String adcreativeElements = records.get(i).getAdcreativeElements();
						Map map = JSONObject.parseObject(adcreativeElements,Map.class);
						//设置imageUrl 空字符串
						String imageId = "";
						//如果adcreativeElements中包含image字符串
						if (adcreativeElements.contains("image") && !adcreativeElements.contains("image_list")){
							imageId = (String) map.get("image");
						}
						if (adcreativeElements.contains("image_list")){
							if (StringUtils.isNotBlank(map.get("image_list").toString())){
								String[] image_list = ((JSONArray)map.get("image_list")).toArray(new String[]{});
								imageId = image_list[0];
							}
						}
						//1 设置imageUrl
						if (StringUtils.isNotBlank(imageId)){
							//通过imageId查询图片url，预览
							AdPicturePlatform picPlatform = adPicturePlatformMapper.selectOne(Wrappers.<AdPicturePlatform>query().lambda()
									.eq(AdPicturePlatform::getPlatformId, 3)
									.eq(AdPicturePlatform::getPlatformPictureId, imageId)
									.last("LIMIT 1"));
							if (Objects.nonNull(picPlatform)){
								records.get(i).setImageUrl(picPlatform.getPlatformPictureUrl());
							}
						}
					}

					//2 设置onOff
					Long adId = records.get(i).getAdId();
					GdtAd gdtAd = gdtAdMapper.selectOne(Wrappers.<GdtAd>query().lambda()
							.eq(GdtAd::getAdId, adId)
							.last("LIMIT 1"));
					//如果mysql有记录。理论上mysql和CH数据是一致的，否则就是同步有问题！
					if (Objects.nonNull(gdtAd)){
						//将mysql的开关状态设置到列表记录中
						records.get(i).setOnOff(gdtAd.getConfiguredStatus());
					}

				}
			}
			//广告创意列表数据放回分页类中
			result.setRecords(records);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(null == result){
			result=new Page<>();
		}
		return R.ok(result,"查询成功");
	}

	/*
	 *  调广点通接口设置广告开关：广告开关字段configured_status
	 * */
	@Override
	public R updateGdtAdOnOff(GdtAdVo req) {
		String onOff = req.getOnOff();
		Long adId = req.getAdId();
		GdtAd gdtAd = gdtAdMapper.selectOne(Wrappers.<GdtAd>query().lambda()
				.eq(GdtAd::getAdId, adId)
				.last("LIMIT 1"));
		if (Objects.isNull(gdtAd)){
			return R.failed("无此广告");
		}

		Map<String, String> map = gdtAccesstokenService.fetchAccesstoken(gdtAd.getAccountId());
		if (map == null || StringUtils.isEmpty(map.get("access_token"))) {
			return R.failed("广点通账户授权失败，请重试！");
		}
		//请求url
		String urlstr = gdtUrl + gdtAdUpdateUrl + "?" + MapUtils.queryString(map);
		log.info("修改广点通广告计划 request:" + urlstr);
		Map<String, Object> params = new HashMap<>();
		params.put("account_id", gdtAd.getAccountId());
		//默认为有效状态
		String configuredStatuType = GdtAdEnum.AD_STATUS_NORMAL.getType();
		String msg = "开启";
		if ("AD_STATUS_SUSPEND".equals(onOff)) {
			//暂停状态
			configuredStatuType = GdtAdEnum.AD_STATUS_SUSPEND.getType();
			msg = "暂停";
		}
		params.put("configured_status", configuredStatuType);
		params.put("ad_id",adId);
		//调用广点通接口，修改开关状态
		String resultStr = OEHttpUtils.doPost(urlstr, params);
		log.info("修改广点通ad开关： response:" + resultStr);
		ResponseBean resBean = JSON.parseObject(resultStr, ResponseBean.class);
		if (StringUtils.equals(resBean.getCode(), "0")) {
			//同步修改数据库(mysql+CH)
			//1 mysql
			gdtAd.setConfiguredStatus(configuredStatuType);
			QueryWrapper<GdtAd> queryWrapper = new QueryWrapper<GdtAd>();
			queryWrapper.eq("ad_id",gdtAd.getAdId());//条件：广告id
			try {
				gdtAdMapper.update(gdtAd,queryWrapper);//修改mysql中gdt_ad表的该广告id记录的configured_status字段
			} catch (Exception e) {
				e.printStackTrace();
				log.info("本地mysql数据库广告开关状态信息修改失败");
			}
			//2 CH nottodo 不支持update
/*			try {
				gdtAdReportMapper.updateByAdIdSelective(gdtAd);
			} catch (Exception e) {
				e.printStackTrace();
			}*/
		}else {
			return R.failed("修改开关状态失败!");
		}
		return R.ok(null,"修改成功");
	}
}
